<template>
<div class="userManage">
 <el-card>
   <el-breadcrumb separator="/">
   <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
   <el-breadcrumb-item>系统管理</el-breadcrumb-item>
  <el-breadcrumb-item>用户管理</el-breadcrumb-item>
   </el-breadcrumb>
    <el-divider></el-divider>
    <div class="serch">
      <el-input style="width:25%;margin-right:30px" v-model="serchinput" placeholder="用户名" ></el-input>
 <el-button type="primary" icon="el-icon-search" @click="serchUser(serchinput)">搜索</el-button>
 <el-button type="primary" icon="el-icon-s-fold" @click="getRolesList" >全部</el-button>
 <el-button type="primary" icon="el-icon-user-solid" @click="isAddUser=!isAddUser" >添加用户</el-button>
    </div>
   
    <div class="roles">
      <el-descriptions style="margin-top:20px" class="margin-top" title="账号信息" :column="3"  border v-for="item in roleList" :key="item._id" >
    <template slot="extra">
      <el-button type="warning" size="small" @click="resetPwd(item.userName)">重置密码</el-button>
      <el-button type="primary" size="small" @click="editMsg(item.userName,item._id,item.tel)" >编辑信息</el-button>
      <el-button type="danger" size="small" @click="deleterole(item.userName)">删除管理</el-button>
    </template>
    <el-descriptions-item>
      <template slot="label">
        <i class="el-icon-user"></i>
        用户名
      </template>
      {{item.userName}}
    </el-descriptions-item>
        <el-descriptions-item>
      <template slot="label">
        <i class="el-icon-ship"></i>
        民族
      </template>
      {{item.nation==''?'暂无':item.nation}}
    </el-descriptions-item>
    <el-descriptions-item>
      <template slot="label">
        <i class="el-icon-location-outline"></i>
        学历
      </template>
      {{item.education==''?'暂无':item.education}}
    </el-descriptions-item>
    <el-descriptions-item>
      <template slot="label">
        <i class="el-icon-tickets"></i>
        备注
      </template>
      <el-tag size="small">{{item.role}}</el-tag>
    </el-descriptions-item>
 <el-descriptions-item>
      <template slot="label">
        <i class="el-icon-mobile-phone"></i>
        手机号
      </template>
     {{item.tel==''?'暂无':item.tel}}
    </el-descriptions-item>
  </el-descriptions>
    </div>
     <el-pagination 
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="currentPage"
      :page-sizes="[1, 2, 10, 20]"
      :page-size="size"
      layout="total, sizes, prev, pager, next, jumper"
      :total=" sizeList.length">
    </el-pagination>
 </el-card>
 <el-dialog
   title="编辑信息"
  :visible.sync="dialogVisible"
  width="30%"
 >
 
  <el-form ref="editForm" :model="editForm" label-width="80px">
  <el-form-item label="用户名">
    <el-input v-model="editForm.name" disabled ></el-input>
  </el-form-item>
  <el-form-item label="电话号码">
    <el-input v-model="editForm.tel"></el-input>
  </el-form-item>
  <el-form-item label="用户权限">
  <el-select v-model="editForm.role" >
    <el-option v-for="item in roleoptions" :key="item.id" :label="item.label" :value="item.value"></el-option>
  </el-select>
  </el-form-item>
  <el-form-item label="学历">
<el-select v-model="editForm.education" >
   <el-option v-for="item in eductionoptions" :key="item.id" :label="item.label" :value="item.value"></el-option>
  </el-select>
      </el-form-item>

    <el-form-item label="民族">
    <el-select v-model="editForm.nation" >
      <el-option v-for="item in nationoptions" :key="item.id" :label="item.label" :value="item.value"></el-option>
  </el-select>
  </el-form-item>
    <el-form-item>
    <el-button type="primary" @click="updataRole">提交</el-button>
    <el-button @click="reset" >重置</el-button>
  </el-form-item>
  </el-form>
 </el-dialog>
  <el-dialog
   title="添加用户"
  :visible.sync="isAddUser"
  width="30%"
 >
<el-form ref="addForm" :model="addForm" label-width="80px" :rules="addrules">
    <el-form-item label="用户名" prop="userName">
    <el-input v-model="addForm.userName"  @input="resetValidate('userName')" ></el-input>
  </el-form-item>
     <el-form-item label="密码" prop="passWord">
    <el-input v-model="addForm.passWord" @input="resetValidate('passWord')" ></el-input>
  </el-form-item>
     <el-form-item label="电话号码">
    <el-input v-model="addForm.tel"  ></el-input>
  </el-form-item>
   <el-form-item label="用户权限">
  <el-select v-model="addForm.role"  style="width:100%" >
    <el-option v-for="item in roleoptions" :key="item.id" :label="item.label" :value="item.value"></el-option>
  </el-select>
  </el-form-item>
  <el-form-item label="学历">
<el-select v-model="addForm.education" style="width:100%" >
   <el-option v-for="item in eductionoptions" :key="item.id" :label="item.label" :value="item.value"></el-option>
  </el-select>
      </el-form-item>

    <el-form-item label="民族">
    <el-select v-model="addForm.nation" style="width:100%" >
      <el-option v-for="item in nationoptions" :key="item.id" :label="item.label" :value="item.value"></el-option>
  </el-select>
  </el-form-item>
      <el-form-item>
    <el-button type="primary" @click="AddUser('addForm')">提交</el-button>
    <el-button  >重置</el-button>
  </el-form-item>
</el-form>
  </el-dialog>
</div>
</template>

<script>
import {mapState,mapMutations} from 'vuex'
export default {
  created() {
    this.openFullScreen2()
    this.getRolesList()
    this.getEductionList()
    this.getNationList()
    this.getPowerList()
   
   
  },
  data() {
    return {
      currentPage:1,
      size:1,
      page:0,
      serchinput:'',
       sizeList:[],
      roleList:[],
      dialogVisible:false,
      editForm:{
        name:'',
        tel:'',
        role:'',
        education:'',
        nation:'',
      },
      addForm:{
        userName:'',
        passWord:'',
        tel:'',
        role:'',
        education:'',
        nation:'',
      },
      addrules:{
        userName: [
            { required: true, message: '请输用户名', trigger: 'blur' },
            { min: 5, message: '长度不少于5位', trigger: 'blur' }
          ],
          passWord:[
              { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, message: '长度不少于6位', trigger: 'blur' }
          ]
      },
      eductionoptions:[
        {id:1111, value:"本科",label:"本科"},
        {id:1111,value:"专科",label:"专科"},
        {id:1111,value:"985",label:"985"},
        {id:1111,value:"211",label:"211"},
      ],
       nationoptions:[
        {value:'1111'},
        {value:'1111'},
        {value:'1111'},
      ],
       roleoptions:[
        {id:1111, value:"超级管理员",label:"超级管理员"},
        {id:1111,value:"高管",label:"高管"},
        {id:1111,value:"普通管理员",label:"普通管理员"},
        {id:1111,value:"项目组员",label:"项目组员"},
      ],
      isAddUser:false
    }
  },
  methods: {
  resetValidate(prop){
    this.$refs.addForm.validateField(prop)
  },
    // 添加用户
    async AddUser(formName){
       this.$refs[formName].validate(async(valid) => {
          if (valid) {
             console.log(this.addForm)
      let list ={userName:this.addForm.userName,passWord:this.addForm.passWord}
      const {data:res} =await this.$http.post('/users/register',list)
      if (res.status==0) {
         this.$message.error("账号已经存在")
         return
      }
      let list2={ name:this.addForm.userName,
        tel:this.addForm.tel,
        role:this.addForm.role,
        education:this.addForm.education,
        nation:this.addForm.nation}
      let {data:res1} =await this.$http.put('/users/roles',list2)
       if (res1.status==0) {
          this.$message.error('添加失败')
          return
       }
       this.$message.success('添加成功')
       this.addForm={
        userName:'',
        passWord:'',
        tel:'',
        role:'',
        education:'',
        nation:'',
      }
       this.addOperation("添加用户")
       this.getRolesList()
      this.isAddUser=!this.isAddUser
              } else {
            console.log('error submit!!');
            return false;
          }
        });
     
 
    },
    // 通过states获取操作对象
      ...mapMutations([
      'putUser'
    ]),
    // 加载
      openFullScreen2() {
        const loading = this.$loading.service({
          lock: true,
          text: '拼命加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        setTimeout(() => {
          loading.close();
        }, 1000);
      },
    // 验证登录token是否还在
    isToken(){
    if (!localStorage.getItem("loginToken")) {
      this.$router.push('/login')
      this.$message.warning("token过期请重新登录！")
      return
    }
    const token =localStorage.getItem("loginToken")
    const result=this.$jwtCode(token)
    this.putUser(result)
    console.log(this.time)
    },
    // 添加操作日志
    async addOperation(opname){
    const list= {userName:this.user,passWord:this.password}
             this.putUser(list)
             const  operation ={name:this.user,password:this.password,time:this.time,operation:opname}
             const {data:res1} =await this.$http.post('/logs/actionlist',operation)
             console.log(res1)
    },
    // 添加错误日志
    async addErrorLog(ername){
      const list= {userName:this.user,passWord:this.password}
             this.putUser(list)
          console.log(ername)
          const errorlog={name:this.user,password:this.password,time:this.time,error:ername}
          const {data:res} =  await this.$http.post('/logs/errorlist',errorlog)
          console.log(res)
    },
    // 重置密码
    async resetPwd(user){
       console.log(user)
        this.$confirm('此操作将重置密码, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
            const {data:res} = await this.$http.put('/users/resetPwd',{name:user})
            this.addOperation("重置密码")
            console.log(this.time)
           if (res.status==1) {
              this.$message({
            type: 'success',
            message: '重置密码成功!'
          });
          
          return
           }
           this.$message({
            type: 'danger',
            message: '重置失败!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    
     },
    //  分页操作
    async handleSizeChange(val) {
       this.size=val
     const {data:res} = await this.$http.get(`/users/pagiNationRoles/${this.page}/${this.size}`)
        this.roleList =res.result
      },
     async handleCurrentChange(val) {
        this.page=val-1
const {data:res} = await this.$http.get(`/users/pagiNationRoles/${this.page}/${this.size}`)
         this.roleList =res.result
      },
    // 获取用户列表
     async getRolesList(){
       try{
  let {data:res}= await  this.$http.get('/users/getroles')
      this.roleList=res
      this.sizeList=res
      this.currentPage=1
       }catch(e){
         this.addErrorLog(e.toString())
       }
    
    },
      // 编辑信息
    editMsg(name,id,tel){
      this.dialogVisible=true
      this.editForm.name=name
      this.editForm.tel=tel
      console.log(id)
      this.addOperation("编辑用户信息")
    },
    // 更新用户
    async updataRole(){
       let {data:res} =await this.$http.put('/users/roles',this.editForm)
       if (res.status==0) {
          this.$message.error('编辑失败')
          return
       }
       this.$message.success('编辑成功')
       this.editForm={
        name:'',
        tel:'',
        role:'',
        education:'',
        nation:'',
      }
       this.getRolesList()
       this.dialogVisible=false
    },
    // 删除用户
     deleterole(name){
       this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(()=>{
            if (name=="admin") {
         this.$message.error('超级管理员不能删除')
       return
      }
      this.$http.delete('/users/roles/'+name).then((res)=>{
        console.log(res)
           if (res.status==0) {
          this.$message.error('删除失败')
         return
       }
       this.addOperation("删除操作")
        this.$message.success('删除成功')
         this.getRolesList()
      })
        })
    
      console.log(name)
     
    },
    // 查询用户
    async serchUser(name){
        let list ={name:name}
        try{
     let {data:res} =await this.$http.post('/users/getserchroles',list)
       this.addOperation("查询用户")
       console.log(res)
       this.roleList=res
        }catch(e){
          this.addErrorLog(e.toString())
        }
    },
    // 获取学历字典
     async getEductionList(){
         const {data:res} =await this.$http.get('/dicitonary/eduction')
         this.eductionoptions=res.result
      },
     // 获取民族字典
      async getNationList(){
         const {data:res} =await this.$http.get('/dicitonary/nation')
         
          this.nationoptions=res.result
      },
       // 获取管理权限字典
      async getPowerList(){
         const {data:res} =await this.$http.get('/dicitonary/power')
 
          this.roleoptions=res.result
      },
       // 重置
  reset(){
    this.editForm.tel=""
    this.editForm.education=""
    this.editForm.role=""
    this.editForm.nation=""
  },
  },
  computed:{
    ...mapState([
      'user',
      'password',
      'time'
    ])
  },
  destroyed() {
    
  },
}
</script>

<style scoped>
.userManage{
  height: 85vh;
  overflow-y: scroll;
}
.el-pagination {
   margin-top: 30px;
}
</style>